<?php
/*
 * --------------------------------------------------------------------
 小微OA系统 - 让工作更轻松快乐 Copyright (c) 2013
 http://www.smeoa.com All rights reserved.
 Author: jinzhu.yin<smeoa@qq.com> Support:
 https://git.oschina.net/smeoa/xiaowei
 ---------------------------------------------------------------------
 */
use sef\controller;
use sef\model;

class crm_contact_controller extends base_controller {
	protected $app_type = "common";
	protected $auth_map = array('read' => 'add,save,edit', 'admin' => 'del_company,del,field_manage,export');

	// 过滤查询字段
	function _search_filter(&$where) {
		$where[] = array('crm_contact.is_del', 'eq', '0');
		$keyword = request('keyword');
		if (!empty($keyword) && empty($where['name'])) {
			$where[] = array('name', 'like', $keyword);
		}
	}

	public function index() {
		$auth = $this -> auth;
		$this -> assign('auth', $auth);

		$model = model('crm_contact');
		$model -> get_contact();
		$where = $this -> _search($model);
		if (method_exists($this, '_search_filter')) {
			$this -> _search_filter($where);
		}

		$where_share[] = array('user_id', 'eq', get_user_id());
		$share_list = model('crm_share') -> where($where_share) -> get_field('contact_id', true);

		$map[] = array('salesman_id', 'eq', get_user_id());

		if (!empty($share_list)) {
			$map[] = array('crm_contact.id', 'in', $share_list);
		}
		$where[] = array('complex', $map, 'or');

		if (request('mode') == 'export') {
			$this -> _index_export($model, $where);
		} else {
			$this -> _list($model, $where);
		}
		$this -> display();
	}

	// 添加客户
	public function add() {

		$user['user_id'] = get_user_id();
		$user['user_name'] = get_user_name();
		$this -> assign('user', $user);

		$model_udf_field = model("udf_field");
		$field_list = $model_udf_field -> get_field_list(1);
		$this -> assign("field_list", $field_list);

		$this -> display();
	}

	protected function _insert($name = APP_NAME) {
		$contact = M('CrmContact');
		$contact -> create();
		$contact -> user_id = get_user_id();
		$contact -> user_name = get_user_name();
		$contact -> create_time = time();
		$contact -> udf_data = model('udf_field') -> get_field_data();
		$result = $contact -> add();
		if ($result) {
			$this -> success('新增成功！');
		}
	}

	protected function _update($name = APP_NAME) {
		$contact = M('CrmContact');
		$contact -> create();
		$contact -> udf_data = model('UdfField') -> get_field_data();
		$result = $contact -> save();
		if ($result) {
			$this -> success('编辑成功！');
		}
	}

	public function get_company_list() {
		$company = M('CrmCompany');
		$key = request('key');
		$where['name'] = array('like', "%{$key}%");
		$where['is_del'] = array('eq', 0);
		$company_list = $company -> field('id,name') -> where($where) -> select();

		$data2['info'] = '';
		$data2['data'] = $company_list;
		$data2['status'] = 1;
		$this -> ajaxReturn($data2);
	}

	public function get_salesman_list() {
		$salesman = model('UserView');
		$key = request('key');
		$where['name'] = array('like', "%{$key}%");
		$where['is_del'] = array('eq', 0);
		$salesman_list = $salesman -> field('id,name') -> where($where) -> select();

		$data2['info'] = '';
		$data2['data'] = $salesman_list;
		$data2['status'] = 1;
		$data2['redirect'] = '';

		$this -> ajaxReturn($data2);
	}

	public function read($id) {
		$plugin['uploader'] = true;
		$plugin['editor'] = true;
		$this -> assign("plugin", $plugin);

		$model = M("CrmContact");
		$vo = $model -> find($id);
		if (empty($vo)) {
			$this -> error("系统错误");
		}

		$field_list = model("UdfField") -> get_data_list(1, $vo['udf_data']);
		$this -> assign("field_list", $field_list);
		$this -> assign("vo", $vo);

		$activity = M('CrmActivity');
		$where['contact_id'] = $id;
		$where['is_del'] = 0;
		$list = $activity -> where($where) -> select();
		$this -> assign('list', $list);

		$where_share['contact_id'] = array('eq', $id);
		$share_user = M('CrmShare') -> where($where_share) -> getField('user_id', true);

		if (!empty($share_user)) {
			$where_list['id'] = array('in', $share_user);
			$share_list = M('User') -> where($where_list) -> getField('name', true);
			$this -> assign('share_list', $share_list);
		}

		$this -> display();

	}

	// 编辑客户
	public function edit($id) {
		$plugin['uploader'] = true;
		$plugin['editor'] = true;
		$this -> assign("plugin", $plugin);

		$model = M("crm_contact");
		$vo = $model -> find($id);

		if (empty($vo)) {
			$this -> error("系统错误");
		}
		$this -> assign("vo", $vo);

		$field_list = model("UdfField") -> get_data_list($vo['folder'], $vo['udf_data']);
		$this -> assign("field_list", $field_list);

		$map['is_del'] = array('eq', '0');
		$list = model("ProductView") -> where($map) -> select();
		foreach ($list as $Key => $val) {
			$product[$val['folder_name']][] = $val['name'];
		}

		$this -> assign('product', $product);
		$this -> display();
	}

	public function edit_contact_save() {

	}

	// 删除客户
	public function del_contact($contact_id) {
		$this -> _del($contact_id, "crm_contact");
	}

	public function add_activity_save() {
		$activity = M('CrmActivity');
		$activity -> create();
		$activity -> create_time = time();

		if ($activity -> add_file == "") {
			$activity -> add_file = 'null';
		}
		$activity -> user_id = get_user_id();
		$activity -> user_name = get_user_name();
		$result = $activity -> add();
		if ($result) {
			$this -> success('新增成功！');
		}
	}

	//转交
	public function transfer() {
		$contact = M('CrmContact');
		$where_contact = $this -> _search($contact);
		if (method_exists($this, '_search_filter')) {
			$this -> _search_filter($where_contact);
		}
		$where_user['is_del'] = array('eq', 0);
		$where_contact['is_del'] = array('eq', 0);
		$auth = $this -> auth;
		if ($auth->admin) {
			$user_list = model("UserView") -> where($where_user_list) -> select();
			$contact_list = M('CrmContact') -> where($where_contact) -> select();

		} elseif ($auth->write) {
			$where_user['dept_id'] = array('eq', get_dept_id());
			$user_list = model("UserView") -> where($where_user) -> select();

			$where_contact['salesman_id'] = array('in', rotate($user_list, 'id'));
			$contact_list = M('CrmContact') -> where($where_contact) -> select();

		} elseif ($auth->read) {
			$where_user['dept_id'] = array('eq', get_dept_id());
			$user_list = model("UserView") -> where($where_user) -> select();

			$where_contact['salesman_id'] = array('eq', get_user_id());
			$contact_list = M('CrmContact') -> where($where_contact) -> select();
		}

		$this -> assign('contact_list', $contact_list);
		$this -> assign("user_list", $user_list);

		$this -> display();
	}

	function transfer_save($contact_id, $user_id) {

		$auth = $this -> auth;
		if ($auth->admin) {
			$user_list = model("UserView") -> where($where_user_list) -> select();
			$contact_list = M('CrmContact') -> where($where_contact) -> select();

		} elseif ($auth->write) {
			$where_user['dept_id'] = array('eq', get_dept_id());
			$user_list = model("UserView") -> where($where_user) -> select();

			$where_contact['salesman_id'] = array('in', rotate($user_list, 'id'));
			$contact_list = M('CrmContact') -> where($where_contact) -> select();

		} elseif ($auth->read) {
			$where_user['dept_id'] = array('eq', get_dept_id());
			$user_list = model("UserView") -> where($where_user) -> select();

			$where_contact['salesman_id'] = array('eq', get_user_id());
			$contact_list = M('CrmContact') -> where($where_contact) -> select();
		}

		$contact_list = rotate($contact_list, 'id');

		$contact_id = array_intersect($contact_list, $contact_id);

		if (empty($contact_id)) {
			$this -> error('非法操作1');
		}

		$user_list = rotate($user_list, 'id');
		if (!in_array($user_id, $user_list)) {
			$this -> error('非法操作2');
		}

		$contact = M('CrmContact');
		$where_contact['id'] = array('in', $contact_id);
		$list = M('CrmContact') -> where($where_contact) -> setField('salesman_id', $user_id);

		if ($list != false) {
			$this -> success('转交成功！');
		} else {
			$this -> error('操作失败');
		}
	}

	function share() {
		$contact = M('CrmContact');
		$where_contact = $this -> _search($contact);
		if (method_exists($this, '_search_filter')) {
			$this -> _search_filter($where_contact);
		}
		$where_user['is_del'] = array('eq', 0);
		$where_contact['is_del'] = array('eq', 0);
		$auth = $this -> auth;
		if ($auth->admin) {
			$user_list = model("UserView") -> where($where_user_list) -> select();
			$contact_list = M('CrmContact') -> where($where_contact) -> select();

		} elseif ($auth->write) {
			$where_user['dept_id'] = array('eq', get_dept_id());
			$user_list = model("UserView") -> where($where_user) -> select();

			$where_contact['salesman_id'] = array('in', rotate($user_list, 'id'));
			$contact_list = M('CrmContact') -> where($where_contact) -> select();

		} elseif ($auth->read) {
			$where_user['dept_id'] = array('eq', get_dept_id());
			$user_list = model("UserView") -> where($where_user) -> select();

			$where_contact['salesman_id'] = array('eq', get_user_id());
			$contact_list = M('CrmContact') -> where($where_contact) -> select();
		}

		$this -> assign('contact_list', $contact_list);
		$this -> assign("user_list", $user_list);

		$this -> display();
	}

	function share_save($contact_id, $user_id) {
		$auth = $this -> auth;
		if ($auth->admin) {
			$user_list = model("UserView") -> where($where_user_list) -> select();
			$contact_list = M('CrmContact') -> where($where_contact) -> select();

		} elseif ($auth->write) {
			$where_user['dept_id'] = array('eq', get_dept_id());
			$user_list = model("UserView") -> where($where_user) -> select();

			$where_contact['salesman_id'] = array('in', rotate($user_list, 'id'));
			$contact_list = M('CrmContact') -> where($where_contact) -> select();

		} elseif ($auth->read) {
			$where_user['dept_id'] = array('eq', get_dept_id());
			$user_list = model("UserView") -> where($where_user) -> select();

			$where_contact['salesman_id'] = array('eq', get_user_id());
			$contact_list = M('CrmContact') -> where($where_contact) -> select();
		}

		$contact_list = rotate($contact_list, 'id');
		$contact_id = array_intersect($contact_list, $contact_id);
		if (empty($contact_id)) {
			$this -> error('非法操作1');
		}

		$user_list = rotate($user_list, 'id');
		$user_id = array_intersect($user_list, $user_id);
		if (empty($user_id)) {
			$this -> error('非法操作2');
		}

		$list = model('CrmContact') -> set_share($contact_id, $user_id);
		if ($list) {
			$this -> success('操作成功！');

		} else {
			$this -> error('操作失败3');
		}
	}

	public function get_share_list($id) {
		$where['contact_id'] = array('eq', $id);
		$data = M("CrmShare") -> where($where) -> getField('user_id', true);

		if ($data !== false) {// 读取成功
			$return['data'] = $data;
			$return['status'] = 1;
			$this -> ajaxReturn($return);
		}
	}

	function import() {
		$opmode = request("opmode");
		if ($opmode == "import") {
			$import_user = array();
			$File = model('File');
			$file_driver = C('DOWNLOAD_UPLOAD_DRIVER');
			$info = $File -> upload($_FILES, C('DOWNLOAD_UPLOAD'), C('DOWNLOAD_UPLOAD_DRIVER'), C("UPLOAD_{$file_driver}_CONFIG"));
			if (!$info) {
				$this -> error('上传错误');
			} else {
				//取得成功上传的文件信息
				//$uploadList = $upload -> getUploadFileInfo();
				Vendor('Excel.PHPExcel');
				//导入thinkphp第三方类库
				$import_file = $info['uploadfile']["path"];
				$import_file = substr($import_file, 1);
				$objPHPExcel = \PHPExcel_IOFactory::load($import_file);
				//$objPHPExcel = \PHPExcel_IOFactory::load('Uploads/Download/Org/2014-12/547e87ac4b0bf.xls');
				$sheetData = $objPHPExcel -> getActiveSheet() -> toArray(null, null, true, true);

				$company = M('CrmCompany') -> getField('name,id');
				$product = M('Product') -> getField('name,id');
				$udf_list = model('UdfField') -> get_field_list(1, 'CrmContact');
				$udf_data_key = $sheetData[1];
				for ($i = 2; $i <= count($sheetData); $i++) {
					$data['name'] = $sheetData[$i]['A'];
					$data['user_id'] = get_user_id();
					$data['user_name'] = get_user_name();
					$data['create_time'] = time();
					$data['company_name'] = $sheetData[$i]['B'];
					$data['company_id'] = $company[$sheetData[$i]['B']];
					$data['dept'] = $sheetData[$i]['C'];
					$data['position'] = $sheetData[$i]['D'];
					$data['office_tel'] = $sheetData[$i]['E'];
					$data['mobile_tel'] = $sheetData[$i]['F'];
					$data['email'] = $sheetData[$i]['G'];

					$data['im'] = $sheetData[$i]['H'];
					$data['product'] = $sheetData[$i]['I'];
					$data['salesman_name'] = get_user_name();
					$data['salesman_id'] = get_user_id();
					$data['remark'] = $sheetData[$i]['K'];

					for ($z = 11; $z < count($udf_data_key); $z++) {
						$k = chr(65 + $z);
						$where['name'] = $udf_data_key[$k];
						$where['controller'] = 'CrmContact';
						$udffield = M('UdfField') -> where($where) -> find();
						$udf_data[$udffield['id']] = $sheetData[$i][$k];
					}
					$data['udf_data'] = json_encode($udf_data);
					M('CrmContact') -> add($data);
				}
				$this -> assign('jumpUrl', get_return_url());
				$this -> success('导入成功！');
			}
		} else {
			$this -> display();
		}
	}

	function _index_export($model, $map) {
		$list = $model -> where($map) -> select();

		$i = 1;
		//导入thinkphp第三方类库
		Vendor('Excel.PHPExcel');
		$objPHPExcel = new \PHPExcel();
		$objPHPExcel -> getProperties() -> setCreator("小微OA");

		$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("A$i", "姓名");
		$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("B$i", "公司");
		$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("C$i", "部门");
		$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("D$i", "职位");
		$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("E$i", "办公电话");
		$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("F$i", "手机");
		$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("G$i", "邮件");
		$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("H$i", "即时聊天");
		$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("I$i", "产品");
		$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("J$i", "业务员");
		$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("K$i", "其他");

		$model_udf_field = model("UdfField");
		$udf_list = $model_udf_field -> get_field_list(1, 'CrmContact');
		foreach ($udf_list as $val) {
			$k++;
			$location = get_cell_location('L', $i, $k);
			$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue($location, $val['name']);
		}
		$k = 'K';
		foreach ($list as $val) {
			$i++;
			$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("A$i", $val['name']);
			$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("B$i", $val['company_name']);
			$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("C$i", $val['dept']);
			$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("D$i", $val['position']);
			$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("E$i", $val['office_tel']);
			$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("F$i", $val['mobile_tel']);
			$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("G$i", $val['email']);
			$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("H$i", $val['im']);
			$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("I$i", $val['product']);
			$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("J$i", $val['salesman_name']);
			$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("K$i", strip_tags($val['remark']));

			$field_list = $model_udf_field -> get_data_list($val["udf_data"]);

			if (!empty($field_list)) {
				foreach ($field_list as $field) {
					$k++;
					$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("$k$i", $field['val']);
				}
			}
		}
		$objPHPExcel -> getActiveSheet() -> setTitle('客户信息');

		// Set active sheet index to the first sheet, so Excel opens this as the first sheet
		$objPHPExcel -> setActiveSheetIndex(0);
		$file_name = "客户信息.xlsx";
		// Redirect output to a client’s web browser (Excel2007)
		header("Content-Type: application/force-download");
		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header("Content-Disposition:attachment;filename =" . str_ireplace('+', '%20', URLEncode($file_name)));
		header('Cache-Control: max-age=0');

		$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		//readfile($filename);
		$objWriter -> save('php://output');
		exit ;
	}

	function del_activity($id) {
		$this -> _del($id, 'CrmActivity');
	}

	function field_manage() {
		$this -> assign("folder_name", "CRM 客户自定义字段管理");
		$this -> _field_manage(1);
	}

	function upload() {
		$this -> _upload();
	}

	function down($attach_id) {
		$this -> _down($attach_id);
	}

}
